import java.util.*;

public class Test {
  public class TreeNode {
      int val;
      TreeNode left;
      TreeNode right;
      TreeNode() {}
      TreeNode(int val) { this.val = val; }
      TreeNode(int val, TreeNode left, TreeNode right) {
          this.val = val;this.left = left;
          this.right = right;
      }
  }
  //平衡二叉树
    //写法一 O(n^2)
    /*public int getHeight(TreeNode root) {
        if(root==null) {
            return 0;
        }
        if(root.left==null&&root.right==null){
            return 1;
        }
        return Math.max(getHeight(root.left),getHeight(root.right))+1;
    }
    public boolean isBalanced(TreeNode root) {
        if(root==null){
            return true;
        }
        int h1 = getHeight(root.left);
        int h2 = getHeight(root.right);
        if(Math.abs(h1-h2)>1) {
            return false;
        }
        return isBalanced(root.left)&&isBalanced(root.right);
    }*/

    //写法二 O(N)
    public boolean isBalanced(TreeNode root) {
        if(root==null){
            return true;
        }
        if(getHeight(root)>=0) {
            return true;
        }
        return false;
    }

    public int getHeight(TreeNode root) {
        if(root==null) {
            return 0;
        }
        if(root.left==null&&root.right==null){
            return 1;
        }
        int h1 = getHeight(root.left);
        int h2 = getHeight(root.right);
        if(h1>=0&&h2>=0&&Math.abs(h1-h2)<=1) {
            return Math.max(h1,h2)+1;
        }else {
            return -1;
        }
    }

    //二叉树层序遍历
    public List<List<Integer>> levelOrder(TreeNode root) {
        List<List<Integer>> list = new ArrayList<>();
        if(root==null) {
            return list;
        }
        Queue<TreeNode> q = new LinkedList<>();
        q.add(root);
        int size = 1;
        while(!q.isEmpty()) {
            List<Integer> t = new ArrayList<>();
            for(int i=0;i<size;i++) {
                TreeNode front = q.poll();
                t.add(front.val);
                if(front.left!=null) {
                    q.add(front.left);
                }
                if(front.right!=null) {
                    q.add(front.right);
                }
            }
            list.add(t);
            size = q.size();
        }
        return list;
    }

    //判断一颗数是不是完全二叉树

}
